//
//  UserAccountModel.swift
//  Weibo
//
//  Created by 张小东 on 16/1/14.
//  Copyright © 2016年 Mr.Zhang. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountModel: NSObject {
    
    var userAccount : UserAccount?
    override init() {
        // 用缓存数据 给模型赋值
        userAccount = UserAccount.loadUserAccount()
        super.init()
    }
    // 用户是否登陆的标记
    // 只读属性 计算性属性
    var userLogin : Bool {
        //根据token是否为空 判断用户是否登陆
        return userAccount?.access_token != nil
    }
    // 从缓存中 获取token
    var token: String? {
        return userAccount?.access_token
    }
    var userName : String? {
        return userAccount?.name
    }
    var headImageURL : NSURL? {
        return NSURL(string: userAccount?.avatar_large ?? "")
    }
    
    
    // 获取授权token
    func loadAccessToken(code: String , finished : (isSuccess: Bool) -> ()) {
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : client_id ,"client_secret" : client_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri": "http://www.itcast.cn"]
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlStr, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            // 将result的 AnyObject类型 转换为 [key : String]类型
            guard let dict = result as? [String : AnyObject] else {
                print("数据格式不匹配")
                finished(isSuccess: false)
                return
            }
            // 程序走到这 证明一定被转换为了字典格式
            // 将获取到的数据保存到字典中
            let account = UserAccount(dict: dict)
            print("--->",account)
            
            //获取用户信息
            self.loadUserInfo(account, finished: finished)
            
            }) { (_, error) -> Void in
                finished(isSuccess: false)
                print(error)
        }
    }
    
    // MARK 加载用户信息
    private func loadUserInfo(account: UserAccount, finished : (isSuccess: Bool) -> ()) {
        //        print(access_token,uid)
        let urlStr = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token" : account.access_token! , "uid" : account.uid!]
        
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlStr, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //            print(result)
            guard let dict = result as? [String : AnyObject] else {
                print("数据类型不匹配")
                finished(isSuccess: false)
                return
            }
            
            let name = dict["name"] as! String
            let avatar_large = dict["avatar_large"] as! String
            account.name = name
            account.avatar_large = avatar_large
            account.saveAccount()
            print("=========== ",account)
            
            finished(isSuccess: true)
            //            print(name,avatar_large)
            
            }) { (_, error) -> Void in
                finished(isSuccess: false)

                print(error)
        }
        
    }
    
}
